package com.yeziji.utils;

import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

/**
 * 异步事务提交
 *
 * @author hwy
 * @since 2023/09/23 0:09
 **/
public class TransactionUtils {
    /**
     * 异步执行事务提交之后的行为
     *
     * @param action 操作行为
     */
    public static void asyncExecuteAfterCommit(Runnable action) {
        // 判断是否真实开启了事务，如果没开启，直接异步执行
        if (!TransactionSynchronizationManager.isActualTransactionActive()) {
            ThreadPoolUtils.customExecute(action);
            return;
        }
        // 开启了事务后等事务提交之后执行 afterCommit
        TransactionSynchronizationManager.registerSynchronization(
                new TransactionSynchronization() {
                    @Override
                    public void afterCommit() {
                        ThreadPoolUtils.customExecute(action);
                    }
                });
    }
}
